# == Schema Information
#
# Table name: users
#
#  id                           :integer          not null, primary key
#  mobile                       :string
#  nickname                     :string
#  name                         :string
#  description                  :text
#  email                        :string
#  password                     :string
#  password_digest              :string
#  encrypted_password           :string
#  password_reset_token         :string
#  password_reset_token_sent_at :date
#  confirmation_token           :string
#  confirmed_at                 :datetime
#  confirmation_sent_at         :datetime
#  sign_in_count                :integer          default(0), not null
#  current_sign_in_at           :datetime
#  last_sign_in_at              :datetime
#  current_sign_in_ip           :string
#  last_sign_in_ip              :string
#  uuid                         :string
#  created_at                   :datetime         not null
#  updated_at                   :datetime         not null
#  default_address_id           :integer
#  position                     :string
#

class User < ApplicationRecord
  include ActiveModel::SecurePassword
  #include ValidateSmsCode, ValidateCaptcha
  include ValidateSmsCode
  include OmniauthCallback

  user_third_party_create_enhance

  has_many :user_roles, dependent: :destroy
  has_many :roles, through: :user_roles
  has_many :user_login_authorizations
  has_many :devices
  has_many :addresses, -> { where(address_type: Address::AddressType::User).without_deleted.order("id desc") }
  has_many :invoices, -> { without_deleted.order("id DESC") }
  belongs_to :default_address, class_name: :Address
  has_many :orders, -> { includes(:invoice).order("updated_at DESC") }
  has_many :payments
  has_many :design_cases

  has_one :avatar

  has_secure_password
  attr_accessor :current_password, :need_current_password,
                :password_confirmation, :in_password_reset,
                :skip_name_validation, :on_mobile,
                :is_third_party_account,
                :auto_register

  validates :mobile, :presence => true, :uniqueness => {:case_sensitive => false}, :format => {:with => /\A1\d{10}\z/, :message => '请输入正确的手机号码'}#, :if => :is_not_third_party_account?
  #validates :name, :presence => true, :format => {:with => /\A.+\z/, :message => '昵称不能含空格或空白字符'}, :on => :update, :if => :not_in_password_reset
  #validates :name, :length => { in: 2..10 }, :on => :update, :if => :not_in_password_reset
  validates :password, :length => { in: 6..20 }, :if => :can_modify_password?
  validates_confirmation_of :password, :message => '重复密码不匹配', :if => :can_modify_password?
  validates :term_of_service, :acceptance => {:accept => true}

  before_create :generate_uuid

  after_create :send_auto_register_sms, if: :auto_register

  def temp_access_token
    Rails.cache.fetch("user-#{id}-temp_access_token-#{Time.now.strftime('%Y%m%d')}") do
      SecureRandom.hex
    end

  end

  def is_designer?
    self.roles.map(&:name).include? "designer"
  end

  def is_admin?
    self.roles.map(&:name).include? "admin"
  end

  def is_not_third_party_account?
    !self.is_third_party_account
  end

  def can_modify_password?
    return false if self.on_mobile
    self.new_record? || in_password_reset
  end

  def not_in_password_reset
    !in_password_reset && !skip_name_validation
  end

  def add_role role
    self.user_roles.create!(role_id: role.id)
  end

  def has_role?(*role_names)
    self.roles.where(:name => role_names).present?
  end

  def remember_token
    [id, Digest::SHA512.hexdigest(password_digest)].join('$')
  end

  def generate_password_reset_token
    update_attributes(
      :password_reset_token => generate_token,
      :password_reset_token_sent_at => Time.now
    )
  end

  def generate_token
    SecureRandom.hex(32)
  end

  def unread_notifications limit=3
    #Notification::Base.where(user_id: self.id).limit(limit).unread
  end

  def get_unread_notifications_count
    #Notification::Base.where(user_id: self.id).unread.count
  end

  def to_s_for_niubi
    "登录总数：#{self.sign_in_count}上\n次登录时间：#{self.last_sign_in_at}\n当前登录IP：#{self.current_sign_in_ip}\n上次登录IP：#{self.last_sign_in_ip}"
  end

  def register_designer
    self.user_roles.create(role: Role.where(name: "designer").first)
  end

  private

  def generate_uuid
    self.uuid = RandomCode.generate_utoken
  end

  def send_auto_register_sms
    puts ">>>" * 30
    puts "AUTO"
    puts ">>>" * 30
  end

  class << self

    def find_by_remember_token(token)
      user = where(:id => token.split('$').first).first
      (user && user.remember_token == token) ? user : nil
    end

    def get_designers limit=5
      User.joins(:user_roles).where("user_roles.role_id = ?", Role.get_designer_role.id).order("users.created_at DESC").limit(limit)
    end

  end

end

